<template>
 <div class="container">
   <el-card shadow="always">
     <div slot="header">
    <span>{{judge}}</span>
  </div>
  <el-form ref="formData" :model="formData" :rules="formRules">
    <el-form-item label="学科:" prop="subjectID">
      <el-select @change="subjectChange" placeholder="请选择" v-model="formData.subjectID">
      <el-option v-for="item in subjectList" :key="item.value" :label="item.label" :value="item.value"></el-option>
    </el-select>
    </el-form-item>
    <el-form-item label="目录:" prop="catalogID">
      <el-select placeholder="请选择"  v-model="formData.catalogID">
      <el-option v-for="item in catalogList" :key="item.value" :label="item.label" :value="item.value"></el-option>
    </el-select>
    </el-form-item>
    <el-form-item label="企业:" prop="enterpriseID">
      <el-select  placeholder="请选择" v-model="formData.enterpriseID">
      <el-option v-for="item in enterpriseList" :key="item.id" :label="item.company" :value="item.id"></el-option>
    </el-select>
    </el-form-item>
    <el-form-item class="area" label="城市:" prop="province">
      <el-select  placeholder="请选择" class="city" v-model="formData.province">
      <el-option v-for="(item,index) in provinceList" :key="index"  :label="item" :value="item"></el-option>
    </el-select>
    </el-form-item>
  <el-form-item class="area" prop="city">
      <el-select @focus="getCity" placeholder="请选择" class="city" v-model="formData.city">
      <el-option v-for="(item,index) in cityList" :key="index"  :label="item" :value="item"></el-option>
    </el-select>
    </el-form-item>
    <el-form-item label="方向:" prop="direction">
      <el-select placeholder="请选择" v-model="formData.direction">
      <el-option v-for="(item,index) in directionList" :key="index" :label="item" :value="item" ></el-option>
    </el-select>
    </el-form-item>
     <el-form-item label="题型:" prop="questionType">
    <el-radio-group @input="qsTypeChange" v-model="formData.questionType">
      <el-radio v-for="item in questionTypeList" :key="item.value" :label="String(item.value)">{{item.label}}</el-radio>
    </el-radio-group>
  </el-form-item>
     <el-form-item label="难度:" prop="difficulty">
    <el-radio-group v-model="formData.difficulty">
      <el-radio v-for="item in difficultyList" :key="item.value" :label="String(item.value)">{{item.label}}</el-radio>
    </el-radio-group>
  </el-form-item>
  <el-form-item  label="题干:" prop="question">
    <quillEditor v-model="formData.question" @blur="quillEditorRules" :options="editorOption"></quillEditor>
  </el-form-item>
  <el-form-item v-if="isShow" label="选项:">
    <!-- 双选 -->
    <template v-if="isCheckout">
     <div class="option_item" >
      <el-checkbox-group v-model="chooseList" @change="getChtRight">
     <el-checkbox :label="item.code" v-for="(item,index) in formData.options" :key="index">
      {{item.code+':'}}
      <el-input v-model="item.title"></el-input>
    <el-upload
  class="upload-demo"
  :show-file-list="false"
  action="#"
   :data="{index}"
  :http-request="uploadUrl"
  >
  <el-button size="small" >点击上传<i class="el-icon-circle-close"></i></el-button>
</el-upload>
</el-checkbox>
      </el-checkbox-group>
   </div>
  </template>

  <!-- 单选 -->
   <template v-else>
    <div  class="option_item" >
       <el-radio-group v-model="chooseCode" @input="getRight">
     <el-radio  :label="item.code" v-for="(item,index) in formData.options" :key="index">{{item.code+':'}}
       <el-input v-model="item.title"></el-input>
    <el-upload
  class="upload-demo"
  :show-file-list="false"
  action="#"
  :data="{index}"
  :http-request="uploadUrl"

  >
<img v-if="formData.options[index].img" :src="formData.options[index].img" class="avatar">
  <el-button size="small"  > <span v-if="!formData.options[index].img">点击上传</span><i class="el-icon-circle-close"></i></el-button>
</el-upload>
     </el-radio>
       </el-radio-group>
   </div>
   </template>

   <el-button class="submitbtn" type="danger" :disabled="!isCheckout" @click="addAnswer">+增加选项与答案</el-button>
  </el-form-item>
  <el-form-item  label="解析视频:" prop="videoURL">
    <el-input style="width:400px" v-model="formData.videoURL"></el-input>
  </el-form-item>
  <el-form-item  label="答案解析:" prop="answer">
    <quillEditor @blur="quillEditorRules2" style="margin-left:70px" :options="editorOption" v-model="formData.answer"></quillEditor>
  </el-form-item>
  <el-form-item label="题目备注:" prop="remarks">
    <el-input v-model="formData.remarks" :autosize="{minRows:5,maxRows:20}" type="textarea"></el-input>
  </el-form-item>
  <el-form-item label="试题标签:" prop="tags">
      <el-select placeholder="请选择" filterable allow-create default-first-option multiple v-model="formData.tags">
      <el-option v-for="item in tagList" :key="item.value" :label="item.label" :value="item.label"></el-option>
    </el-select>
    </el-form-item>
    <el-form-item label="">
      <el-button @click="doSubmit" style="margin-left:70px" :type="isEdit ? 'success' : 'primary'">{{button}}</el-button>
    </el-form-item>
  </el-form>
  </el-card>
 </div>
</template>

<script>
// require styles
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'
import { simple } from '@/api/hmmm/subjects'
import { list } from '@/api/hmmm/companys'
import { simple as simpleCatelog } from '@/api/hmmm/directorys'
import { provinces, citys } from '@/api/hmmm/citys'
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
import { simple as simpleTags } from '@/api/hmmm/tags'
import { add, detail, update } from '@/api/hmmm/questions'
// import COS from 'cos-js-sdk-v5'

const COS = require('cos-js-sdk-v5')
const cos = new COS({
  SecretId: 'AKIDlOp20jOuEJ5iANK4buyrZ6PZbQ2Sefux',
  SecretKey: 'vfBUdbQ2UiknkT1MUOBoDPN7dw2uZ2IK'
})
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      // form表单
      formData: {
        // 学科
        subjectID: '',
        // 目录
        catalogID: '',
        // 企业
        enterpriseID: '',
        // 城市
        province: '',
        // 地区
        city: '',
        // 方向
        direction: '',
        // 题型
        questionType: '1',
        // 难度
        difficulty: '1',
        // 题干
        question: '',
        // 选择
        options: [{
          // 选项
          code: 'A',
          // 文字
          title: '',
          // 图片
          img: '',
          // 是否正确
          isRight: false
        },
        {
          // 选项
          code: 'B',
          // 文字
          title: '',
          // 图片
          img: '',
          // 是否正确
          isRight: false
        },
        {
          // 选项
          code: 'C',
          // 文字
          title: '',
          // 图片
          img: '',
          // 是否正确
          isRight: false
        },
        {
          // 选项
          code: 'D',
          // 文字
          title: '',
          // 图片
          img: '',
          // 是否正确
          isRight: false
        }
        ],
        // 视频
        videoURL: '',
        // 解析
        answer: '',
        // 备注
        remarks: '',
        // 标签
        tags: []
      },
      formRules: {
        subjectID: [{ required: true, trigger: 'change', message: '请输入学科' }],
        catalogID: [{ required: true, trigger: 'change', message: '请输入目录' }],
        enterpriseID: [{ required: true, trigger: 'change', message: '请输入企业' }],
        province: [{ required: true, trigger: 'change', message: '请输入城市' }],
        city: [{ required: true, trigger: 'change', message: '请输入地区' }],
        direction: [{ required: true, trigger: 'blur', message: '请输入方向' }],
        questionType: [{ required: true, trigger: 'change', message: '请输入题型' }],
        difficulty: [{ required: true, trigger: 'change', message: '请输入难度' }],
        question: [{ required: true, message: '请输入题干' }],
        answer: [{ required: true, trigger: 'blur', message: '请输入解析' }],
        tags: [{ required: true, trigger: 'change', message: '请输入标签' }]
      },
      // 学科列表
      subjectList: [],
      // 目录列表
      catalogList: [],
      // 企业列表
      enterpriseList: [],
      // 城市列表
      provinceList: provinces(),
      cityList: [],
      // 枚举
      directionList: direction,
      questionTypeList: questionType,
      difficultyList: difficulty,
      // 是否双选
      isCheckout: false,
      // 是否显示选项
      isShow: true,
      // 选项传值index
      chooseCode: '',
      chooseList: [],
      // 字母变量
      letter: 68,
      // 标签列表
      tagList: [],
      value: '',
      // 定义富文本选框
      editorOption: {
        modules: {
          toolbar: {
            container: [
              // 自定义工具栏选项
              // 工具栏设置
              ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线

              //  [{ 'header': 1 }, { 'header': 2 }],        // 标题，键值对的形式；1、2表示字体大小
              [{ list: 'ordered' }, { list: 'bullet' }], // 列表
              ['blockquote', 'code-block'], // 引用，代码块
              // [{ align: [] }], // 对齐方式
              // [{ script: 'sub' }, { script: 'super' }], // 上下标
              // ['clean'], // 清除字体样式

              // [{ 'indent': '-1'}, { 'indent': '+1' }],     // 缩进
              //  [{ 'direction': 'rtl' }],             // 文本方向

              // [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
              // [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
              // [{ header: [1, 2, 3, 4, 5, 6, false] }], // 几级标题
              // [{ font: [] }], // 字体

              ['image', 'link'] // 上传图片、上传视频
              // ['revoke', 'redo'] // 添加的按钮
            ],
            handlers: {
              // 给自定义按钮添加的事件
              revoke: () => {
                // 撤销
                this.btnundo()
              },
              redo: () => {
                // 恢复
                this.btnRedo()
              }
            }
          }
        }
      },
      isEdit: false
    }
  },
  computed: {
    judge () {
      return this.isEdit ? '试题修改' : '新增试题'
    },
    button () {
      return this.isEdit ? '确认修改' : '确实提交'
    }
  },
  async created () {
    console.log(1)
    if (this.$route.query.id) {
      this.isEdit = true
      console.log(this.$route.query.id)
      await this.getInfo()
    }
    this.getSubject()
    this.getCatalog()
    this.getEnterprise()
    this.getRight()
  },
  mounted () {

  },
  methods: {
    // 获取详情
    async getInfo () {
      const { data } = await detail({ id: this.$route.query.id })
      console.log(data)
      this.formData = { ...data, tags: [] }
    },
    // 编辑
    async updateQuestions () {
      const r = await update({ ...this.formData, tags: JSON.stringify(...this.formData.tags) })
      console.log(r)
    },
    // 富文本校验
    quillEditorRules () {
      this.$refs.formData.validateField('question')
    },
    quillEditorRules2 () {
      this.$refs.formData.validateField('answer')
    },
    // 学科列表
    async  getSubject () {
      const { data } = await simple()
      this.subjectList = data
    },
    // 目录列表
    async getCatalog () {
      if (!this.formData.subjectID) return
      const { data } = await simpleCatelog({ id: this.formData.subjectID })
      this.catalogList = data
    },
    // 企业列表
    async getEnterprise () {
      const { data } = await list({ pagesize: 1000 })
      this.enterpriseList = data.items
    },
    // 城市列表
    getCity () {
      if (!this.formData.province) return
      this.cityList = citys(this.formData.province)
    },
    // 控制显示
    qsTypeChange (value) {
      if (value === '1') {
        this.isShow = true
        this.isCheckout = false
      } else if (value === '2') {
        this.isShow = true
        this.isCheckout = true
      } else if (value === '3') {
        this.isShow = false
      }
    },
    // 单选框
    getRight (code) {
      // this.formData.options.
      console.log(code)
      this.formData.options.map(item => {
        item.isRight = false
        if (code === item.code) {
          item.isRight = true
        }
      })
    },
    // 复选框
    getChtRight (arr) {
      console.log(arr)
      this.formData.options.map(item => {
        arr.forEach(right => {
          if (item.code === right) {
            item.isRight = true
          } else {
            item.isRight = false
          }
        })
      })
    },
    // 添加选项
    addAnswer () {
      this.formData.options.push({
        // 选项
        code: String.fromCharCode((this.letter += 1)),
        // 文字
        title: '',
        // 图片
        img: '',
        // 是否正确
        isRight: false
      })
    },
    // 上传图片
    uploadUrl (res) {
      if (res.file) {
        cos.putObject({
          Bucket: 'hr-88-1316924457', /* 必须 */
          Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
          Key: res.file.name, /* 必须 */
          StorageClass: 'STANDARD',
          Body: res.file, // 上传文件对象
          onProgress: function (progressData) {
            console.log(JSON.stringify(progressData))
          }
        }, (err, data) => {
          console.log(err || data)
          console.log(this.formData.options[res.data.index])
          this.formData.options[res.data.index].img = `http://${data.Location}`
        })
      }
    },
    // 清空表单
    resetForm () {
      this.$refs.formData.resetFields()
      this.formData = {
        // 学科
        subjectID: '',
        // 目录
        catalogID: '',
        // 企业
        enterpriseID: '',
        // 城市
        province: '',
        // 地区
        city: '',
        // 方向
        direction: '',
        // 题型
        questionType: '1',
        // 难度
        difficulty: '1',
        // 题干
        question: '',
        // 选择
        options: [{
          // 选项
          code: 'A',
          // 文字
          title: '',
          // 图片
          img: '',
          // 是否正确
          isRight: false
        },
        {
          // 选项
          code: 'B',
          // 文字
          title: '',
          // 图片
          img: '',
          // 是否正确
          isRight: false
        },
        {
          // 选项
          code: 'C',
          // 文字
          title: '',
          // 图片
          img: '',
          // 是否正确
          isRight: false
        },
        {
          // 选项
          code: 'D',
          // 文字
          title: '',
          // 图片
          img: '',
          // 是否正确
          isRight: false
        }
        ],
        // 视频
        videoURL: '',
        // 解析
        answer: '',
        // 备注
        remarks: '',
        // 标签
        tags: ''
      }
    },
    // 封装方法
    // uploadSubjectList (num) {
    //   const arr = []
    //   this.subjectList.map(item => {
    //     arr[item.value] = item.label
    //   })
    //   console.log(arr[num])
    //   return arr[num]
    // },
    async subjectChange () {
      // subjectName: this.uploadSubjectList(this.formData.subjectID)
      // subjectID: this.formData.subjectID
      this.getCatalog()
      const data = await simpleTags({ subjectID: this.formData.subjectID })
      this.tagList = data.data
    },
    // 提交
    doSubmit () {
      this.$refs.formData.validate(async (valid) => {
        if (valid) {
          console.log('通过')
          if (this.formData.id) {
            this.updateQuestions()
          } else {
            await add({ ...this.formData, tags: JSON.stringify(...this.formData.tags) })
          }

          this.resetForm()
          this.$router.push('/questions/list')
        }
      })
    }
  }
}
</script>

<style scoped lang='less'>
.container{
  padding: 20px;
  .el-form{
    padding-left: 50px;
    .area{
      display: inline-block;
      width: 255px;
    }
    .el-select{
      width: 400px;
    }
    .city{
      margin-right: 2px;
      width: 198px;
      height: 36px;
    }
    ::v-deep .quill-editor{
      height: 200px;
      width: 900px;
      margin-left: 50px;
      margin-bottom: 100px;
    }
     .submitbtn{
      margin-left: 45px;
      font-size: 12px;
        width: 122px;
        height: 31px;
      }
    .option_item{

      padding-bottom: 20px;
      margin-left: 45px;
      .el-checkbox{
        margin-right: 10px;
        margin-bottom: 20px;
      }
 .el-radio{
     display: block;
  margin-bottom: 20px;
      margin-right: 10px;
    }
    .el-input{
      width: 240px;
    }
    .upload-demo{
      margin-left: 10px;
      width: 300px;
      display: inline-block;
position: relative;
      i{
        font-size: 20px;
        position: absolute;
        right: -10px;
        top: -10px;
      }

      .el-button{

       width: 100px;
       height: 60px;
       padding: 0;
       border-radius: 7px;
        border: 1px dashed #DCDFE6;
position: relative;
      }
      img{
          position: absolute;
          left: 0;
          top: 0;
          width: 100px;
          height: 60px;
          z-index: 99;
        }
    }
    }
    .el-textarea{
      width: 400px;
    }
  }
  .el-form-item__label{
    padding-right: 12px;
  }
}
</style>
